<script setup>
    import {
        Management,
        Promotion,
        UserFilled,
        User,
        Crop,
        EditPen,
        SwitchButton,
        CaretBottom
    } from '@element-plus/icons-vue'
    import avatar from '@/assets/default.png'
    import {useTokenStore} from "@/store/token.js";
    //条目被点击后,调用的函数
    import {useRouter} from 'vue-router'
    const router = useRouter();
    const tokenStore = useTokenStore()
    import {ElMessage, ElMessageBox} from 'element-plus'

    const handleCommand = (command) => {
        //判断指令
        if (command === 'logout') {
          tokenStore.removeToken()
            //退出登录
          router.push('/login')
        }else if (command === 'info') {
          dialogForInfo.value = true
          Object.assign(researchers.value,researchersInfoStore.researchers)
        }else if (command === 'resetPassword') {
          resetPasswordDialog.value = true
        }
        else {
            //路由
            router.push('/researchers'+command)
        }
    }

    //查询用户信息,并放到pinia里

    import {useResearchersInfoStore} from "@/store/researchersInfo.js";
    import {researchersApi} from "@/api/researchers.js";
    import {nextTick, reactive, ref} from "vue";
    import {useSizeProps as rawFile} from "../../.vite/deps/element-plus.js";
    const researchersInfoStore = useResearchersInfoStore()
    const researchersInfo = () => {
      researchersApi.researchersInfo().then(result => {
        researchersInfoStore.setResearchersInfo(result.data)
      })
    }
    researchersInfo()

    //修改个人信息
    const researchers = ref({})
    const dialogForInfo = ref(false)
    const updateInfo = () => {
      researchersApi.update(researchers.value).then(result => {
        if (result.code == 0){
          ElMessage.success("update success")
          dialogForInfo.value=false
          researchersInfo()
        }else {
          ElMessage.error("update error")
        }
      })
    }
    //upload avatar
    const headers = ref({
      //携带token传递到后端
      Authorization: tokenStore.token
    })
    import {Plus} from '@element-plus/icons-vue'


    function handleAvatarSuccess(result){
      console.log(result.data)
      researchers.value.avatar = result.data
    }
    const beforeAvatarUpload = () => {
      if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
      }
      return true
    }

    //修改密码
    const resetPasswordDialog = ref(false)
    const passwords = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    });

    const rules = {
      oldPassword: [
        { required: true, message: '请输入旧密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
        { pattern: /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,20}$/, message: '密码必须包含字母、数字和特殊字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
        { validator: (rule, value, callback) => {
            if (value !== passwords.newPassword) {
              callback(new Error('两次输入的密码不一致!'));
            } else {
              callback();
            }
          }, trigger: 'blur' }
      ]
    };
    const changePassword = (passwords) => {
      console.log(passwords)
      researchersApi.resetPassword(passwords).then(result => {
        if (result.code == 0){
          ElMessage.success("修改成功")
          resetPasswordDialog.value=false
          resetPasswordForm();
        }else {
          ElMessage.error(result.msg)
        }

      })
    }
    //重置对话框
    const passwordForm = ref(null);
    const formRef = ref(null);
    const resetPasswordForm = async () => {
      await nextTick(); // Wait for the DOM to update
      if (passwordForm.value) {
        passwordForm.value.resetFields();
      }
      // Reset the reactive form data
      Object.keys(passwords).forEach(key => {
        passwords[key] = '';
      });
    };
</script>

<template>
    <!-- element-plus中的容器 -->
    <el-container class="layout-container">
        <!-- 左侧菜单 -->
        <el-aside width="200px">
            <div class="el-aside__logo"></div>
            <!-- element-plus的菜单标签 -->
            <el-menu active-text-color="#ffd04b" background-color="#232323" text-color="#fff"
                     router>
              <el-menu-item index="/researchers">
                <el-icon>
                  <Promotion/>
                </el-icon>
                <span>我的项目</span>
              </el-menu-item>
              <el-menu-item index="/process">
                <el-icon>
                  <Promotion/>
                </el-icon>
                <span>过程管理</span>
              </el-menu-item>
                <el-sub-menu>
                    <template #title>
                        <el-icon>
                            <UserFilled/>
                        </el-icon>
                        <span>个人中心</span>
                    </template>
                    <el-menu-item index="/user/info">
                        <el-icon>
                            <User/>
                        </el-icon>
                        <span>基本资料</span>
                    </el-menu-item>
                    <el-menu-item index="/user/avatar">
                        <el-icon>
                            <Crop/>
                        </el-icon>
                        <span>更换头像</span>
                    </el-menu-item>
                    <el-menu-item index="/user/resetPassword">
                        <el-icon>
                            <EditPen/>
                        </el-icon>
                        <span>重置密码</span>
                    </el-menu-item>
                </el-sub-menu>
            </el-menu>
        </el-aside>
        <!-- 右侧主区域 -->
        <el-container>
            <!-- 头部区域 -->
            <el-header>
                <div><strong>思途后台管理系统{{ researchersInfoStore.researchers.name }}</strong></div>
                <!-- 下拉菜单 -->
                <!-- command: 条目被点击后会触发,在事件函数上可以声明一个参数,接收条目对应的指令 -->
                <el-dropdown placement="bottom-end" @command="handleCommand">
                    <span class="el-dropdown__box">
                         <el-avatar :src="researchersInfoStore.researchers.avatar?researchersInfoStore.researchers.avatar:avatar"/>
                        <el-icon>
                            <CaretBottom/>
                        </el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="info" :icon="User">基本资料</el-dropdown-item>
                            <el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item>
                            <el-dropdown-item command="resetPassword" :icon="EditPen">重置密码</el-dropdown-item>
                            <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </el-header>
            <!-- 中间区域 -->
            <el-main>
                <!-- <div style="width: 1290px; height: 570px;border: 1px solid red;">
                    内容展示区
                </div> -->
                <router-view></router-view>
            </el-main>
            <!-- 底部区域 -->
            <el-footer>后台管理 ©2024 Created by zhang</el-footer>
        </el-container>
    </el-container>

<!--个人信息对话框-->
  <el-dialog v-model="dialogForInfo" title="Shipping address" width="500">
    <el-form :model="researchers">
      <el-form-item label="Promotion name" :label-width="formLabelWidth">
        <el-input v-model="researchers.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="avatar">
        <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="headers"
        >
          <img v-if="researchers.avatar" :src="researchers.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogForInfo = false">Cancel</el-button>
        <el-button type="primary" @click="updateInfo">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>

<!-- 修改密码对话框 -->
  <el-dialog v-model="resetPasswordDialog" title="修改密码" width="500" @close="resetPasswordForm">
    <el-form ref="passwordForm" :model="passwords" :rules="rules">
      <el-form-item prop="oldPassword" label="old password" :label-width="formLabelWidth">
        <el-input v-model="passwords.oldPassword" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="newPassword" label="new password" :label-width="formLabelWidth">
        <el-input v-model="passwords.newPassword" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="confirmPassword" label="confirm password" :label-width="formLabelWidth">
        <el-input v-model="passwords.confirmPassword" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetPasswordDialog = false">Cancel</el-button>
        <el-button type="primary" @click="changePassword(passwords)">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

  .layout-container {
    height: 100vh;

    .el-aside {
      background-color: #232323;

      &__logo {
        height: 120px;
        background: url('@/assets/logo.png') no-repeat center / 120px auto;
      }

      .el-menu {
        border-right: none;
      }
    }

    .el-header {
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .el-dropdown__box {
        display: flex;
        align-items: center;

        .el-icon {
          color: #999;
          margin-left: 10px;
        }

        &:active,
        &:focus {
          outline: none;
        }
      }
    }

    .el-footer {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      color: #666;
    }
  }


.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style >

</style>